import sys, os, urllib, urllib2, re
DEVELOP = True
DEVELOP = False
# version="2.3.0" 2012/06/04

if not DEVELOP:
	import xbmc, xbmcgui, xbmcplugin, xbmcaddon

# Plugin constants 
#__addonname__ = "empflix.com"
#__addonid__ = "plugin.video.emplix"
#__addon__ = xbmcaddon.Addon(id=__addonid__)

UserAgent = 'Mozilla/5.0 (Windows; U; Windows NT 5.1; en-GB; rv:1.9.0.3) Gecko/2008092417 Firefox/3.0.3'
ORDER_LIST = [['0','Most Recent'], ['1','Being Watched'], ['2','Most Viewed'], ['3','Top Rated']]

if not DEVELOP:
	Addon = xbmcaddon.Addon( id=os.path.basename( os.getcwd() ) )

def GetHttpData(url):
    req = urllib2.Request(url)
    req.add_header('User-Agent', UserAgent)
    response = urllib2.urlopen(req)
    httpdata = response.read()
    if response.headers.get('content-encoding', None) == 'gzip':
        httpdata = gzip.GzipFile(fileobj=StringIO.StringIO(httpdata)).read()
    response.close()
    match = re.compile('<meta http-equiv="[Cc]ontent-[Tt]ype" content="text/html; charset=(.+?)"').findall(httpdata)
    if len(match)<=0:
        match = re.compile('meta charset="(.+?)"').findall(httpdata)
    if len(match)>0:
        charset = match[0].lower()
        if (charset != 'utf-8') and (charset != 'utf8'):
            httpdata = unicode(httpdata, charset).encode('utf8')
    return httpdata


def CATEGORIES():
	link = GetHttpData('http://www.empflix.com/browse.php')
#	match=re.compile('<li><a.+?href="(.+?/channels/.+?)">(.+?)</a></li>').findall(link)
	match=re.compile('<li><a.+?href="(.+?/categories/.+?)">(.+?)</a></li>').findall(link)
	addDir('All','http://www.empflix.com/browse.php?category=mr',1,'',1, 0)
	for channel,name in match:
		addDir(name,channel+"?category=mr",2,'',1, 0)
	if not DEVELOP:
		xbmcplugin.endOfDirectory(int(sys.argv[1]))


def SORTMETHOD(url):
	if DEVELOP:
		print url
		print ORDER_LIST
	else:
		change = False
		dialog = xbmcgui.Dialog()
		list = [x[1] for x in ORDER_LIST]
		sel = dialog.select('Sort Order', list)
		if sel != -1:
			order = ORDER_LIST[sel][0]
			change = True
		if change:
			VIDEOLIST(url,1,order)
        
                       
def VIDEOLIST(url,page,order):
	newurl =  re.sub("-(\d+).html", "-"+str(page)+".html", url)
	if (int(order)==0):
		newurl=re.sub("new-|watched-|popular-|rated-","new-",newurl)
		newurl=re.sub("category=(mr|bw|mv|tr)","category=mr",newurl)
	if (int(order)==1):
		newurl=re.sub("new-|watched-|popular-|rated-","watched-",newurl)
		newurl=re.sub("category=(mr|bw|mv|tr)","category=bw",newurl)
	if (int(order)==2):
		newurl=re.sub("new-|watched-|popular-|rated-","popular-",newurl)
		newurl=re.sub("category=(mr|bw|mv|tr)","category=mv",newurl)
	if (int(order)==3):
		newurl=re.sub("new-|watched-|popular-|rated-","rated-",newurl)
		newurl=re.sub("category=(mr|bw|mv|tr)","category=tr",newurl)

	if DEVELOP:
		print newurl
	link = GetHttpData(newurl)
	addDir('Change Current Sort Order: [COLOR FFFF0000]' + ORDER_LIST[int(order)][1] + '[/COLOR]' ,url, 1,'',1, order)

	#match=re.compile('<a href="(http://www.empflix.com/videos/.+?)".+?title="(.+?)"><img src="(.+?)"').findall(link)
	match=re.compile('<a href="(http://www.empflix.com/videos/.+?)".+?title="(.+?)"><img src=".+?" data-src="(.+?)"').findall(link)
	for videourl,name,thumb in match:
		addLink(name,videourl,3,thumb.strip())
	if (len(match) >= 24):
		addDir('Next Page',url,2,'',page+1, order)
	if (page > 1):
		addDir('Prev Page',url,2,'',page-1, order)
	if not DEVELOP:
		xbmcplugin.endOfDirectory(int(sys.argv[1]))

def PLAYVIDEO(url):
	link = GetHttpData(url)
	# <a href="http://cdn.empflix.com/empdl/f98e0677c657b2636121-1/mosaic_HanaHaruna_Maid_Love_TEK028.flv?key=84707fd382fd95e9fc59a96713567cbf&cd=u" class="downloadButton">Download FLV</a
	#match=re.compile('<a href="(http:.+?)" class="downloadButton">Download FLV</a>').findall(link)
	match=re.compile('flashvars.config = escape."(http:.+?)".;').findall(link)
	for flashurl in match:
		if DEVELOP:
			link = GetHttpData(flashurl)
			matchlink=re.compile('<videoLink>(http:.+?)</videoLink>').findall(link)
			print matchlink
		else:
			link = GetHttpData(flashurl)
			matchlink=re.compile('<videoLink>(http:.+?)</videoLink>').findall(link)
			for videourl in matchlink:
				xbmc.Player().play(videourl)

def get_params():
	param=[]
	paramstring=sys.argv[2]
	if len(paramstring)>=2:
		params=sys.argv[2]
		cleanedparams=params.replace('?','')
		if (params[len(params)-1]=='/'):
			params=params[0:len(params)-2]
		pairsofparams=cleanedparams.split('&')
		param={}
		for i in range(len(pairsofparams)):
			splitparams={}
			splitparams=pairsofparams[i].split('=')
			if (len(splitparams))==2:
				param[splitparams[0]]=splitparams[1]
	return param

def addLink(name,url,mode,iconimage):
	u=sys.argv[0]+"?url="+urllib.quote_plus(url)+"&mode="+str(mode)+"&name="+urllib.quote_plus(name)
	ok=True
	if DEVELOP:
		print "addLink :" + urllib.unquote_plus(url) + "  &mode=" +str(mode)
	else:
		liz=xbmcgui.ListItem(name, iconImage="DefaultFolder.png", thumbnailImage=iconimage)
		ok=xbmcplugin.addDirectoryItem(handle=int(sys.argv[1]),url=u,listitem=liz,isFolder=False)
	return ok

def addDir(name,url,mode,iconimage,page,order):
	u=sys.argv[0]+"?url="+urllib.quote_plus(url)+"&mode="+str(mode)+"&name="+urllib.quote_plus(name)+"&page="+str(page)+"&order="+str(order)
	ok=True
	if DEVELOP:
		print "addDir :"  + urllib.unquote_plus(url) + "  &name=" +str(name) + "  &mode=" +str(mode) + "  &page=" +str(page) + "  &order=" +str(order)
	else:
		liz=xbmcgui.ListItem(name, iconImage="DefaultFolder.png", thumbnailImage=iconimage)
		ok=xbmcplugin.addDirectoryItem(handle=int(sys.argv[1]),url=u,listitem=liz,isFolder=True)
	return ok

def main():
	if not DEVELOP:
		params=get_params()
	url=None
	name=None
	mode=None
	order=0
	page=1

	try:
		url=urllib.unquote_plus(params["url"])
	except:
		pass
	try:
		name=urllib.unquote_plus(params["name"])
	except:
		pass
	try:
		mode=int(params["mode"])
	except:
		pass
	try:
		order=int(params["order"])
	except:
		pass
	try:
		page=int(params["page"])
	except:
		pass

	if mode==None or url==None or len(url)<1:
		if DEVELOP:
			CATEGORIES()
			SORTMETHOD('http://www.empflix.com/categories/watched-asian-1.html')
			VIDEOLIST('http://www.empflix.com/categories/watched-asian-1.html',10, 2)
			PLAYVIDEO('http://www.empflix.com/videos/Filipina-Virgin-66044.html')
		else:
			# Read Password via a keyboard
			keyboard = xbmc.Keyboard("", heading = "Please type your password", hidden = True)
			keyboard.setHeading('Password') # optional
			keyboard.setHiddenInput(True) # optional
			keyboard.doModal()
			if (keyboard.isConfirmed()):
    				inputText = keyboard.getText()
 	   			# set password parameter
    				Password = inputText
				if inputText == "1234":
					LOGINOK = True
				else:
    					dialogInfo = xbmcgui.Dialog()
    					LoginMessage = "Wrong Password"
					LOGINOK = False
  	  				dialogInfo.ok("Password", LoginMessage)
				keyboard.setHiddenInput(False) # optional
				del keyboard
			else:
				return

			if LOGINOK:
				CATEGORIES()
			else:
				return

	elif mode==1:
		SORTMETHOD(url)
                
	elif mode==2:
		VIDEOLIST(url,page,order)

	elif mode==3:
		PLAYVIDEO(url)

if __name__ == "__main__":
    main()
